#include "bsp_esp.h"

void bsp_esp_init(void)
{
	printf("AT+RESTORE\r\n");
	HAL_Delay(1000);
	printf("AT+CWMODE=1\r\n");
	HAL_Delay(3000);
	printf("AT+CWJAP=\"lujunjie\",\"66668888\"\r\n");
	HAL_Delay(3000);


	printf("AT+MQTTUSERCFG=0,1,\"ledtest\",\"admin\",\"JS123456\",0,0,\"\"\r\n");
	HAL_Delay(3000);


	printf("AT+MQTTCONN=0,\"47.97.105.221\",1883,1\r\n");
	HAL_Delay(3000);

	printf("AT+MQTTSUB=0,\"LED1\",0\r\n");
	HAL_Delay(3000);

	printf("AT+MQTTPUB=0,\"LED1\",\"message\",0,0\r\n");
	HAL_Delay(3000);
}


/**
  * @brief          esp8266接收数据
  * @param		      data topic payload
  * @retval         none
  */
void esp8266_receive_msg(char *data, char *topic, char *payload)
{
    // 使用逗号分割字符串
    // strtok 会修改原始字符串，所以如果需要保留原始数据，请先备份
    char *token = strtok(data, ",");
    int tokenCount = 0;

    while (token != NULL)
    {
        tokenCount++;
        // tokenCount==2 表示第二个字段，即 "subtest"
        if (tokenCount == 2)
        {
            // 去掉两端可能存在的双引号
            if (token[0] == '\"')
            {
                token++; // 跳过起始双引号
            }
            // 如果末尾还有双引号，则置为结束符
            char *endQuote = strchr(token, '\"');
            if (endQuote)
            {
                *endQuote = '\0';
            }
            strcpy(topic, token);
        }
        // tokenCount==4 表示第四个字段，即 hello world
        else if (tokenCount == 4)
        {
            strcpy(payload, token);
        }

        token = strtok(NULL, ",");
    }
}

